package ctrLayer;

import modelLayer.Owner;
import modelLayer.Tree;
import modelLayer.TreeContainer;

/**
 * ForestCtr is responsible for the interaction with the modelLayer
 * @author Thomas
 * @version 1.0.0
 */
public class TreeCtr {

	private TreeContainer tCon;
	private static TreeCtr instance;
	
	public TreeCtr () {
		tCon = TreeContainer.getInstance();
	}
	
	/**
	 * singleton
	 * @return instance
	 */
	public static TreeCtr getInstance() {
		if(instance == null) {
			instance = new TreeCtr();
		}
		return instance;
	}
	
	/**
	 * Creates a tree and adds it to the container
	 * @param sort
	 * @param lifespan
	 * @param costPrSquareKilometre
	 * @param revenuePrSquareKilometre
	 * @return
	 */
	public boolean createTree(String sort, int lifespan, double costPrSquareKilometre, double revenuePrSquareKilometre) {
		boolean resultat = false;
		try {
			Tree tree = new Tree(sort, lifespan, costPrSquareKilometre, revenuePrSquareKilometre);
			tCon.addTree(tree);
		}catch (Exception e) {
			resultat = false;
		}
		return resultat;
	}
	
	/**
	 * Find tree method
	 * @param id
	 * @return
	 */
	public Tree findTree(int id) {
		
		int index = 0;
		boolean found = false;
		while(index < tCon.getTrees().size() && found != true) {
			Tree t = tCon.getTree(index);
			if(t.getId() == id) {
				found = true;
			} else {
				index++;
			}
			if(found = true) {
				return tCon.getTree(index);
			}
		}
		return null;
	}
	
	/**
	 * Method that adds the trees to a 2 dimensional array, so it can be used in Jtable
	 * @return
	 */
	public String [][] treeListToArray() {
		int index = 0;
		String data[][] = new String[tCon.getTrees().size()][5];
		while(index < tCon.getTrees().size()) {
			Tree t = tCon.getTree(index);
			
			data[index][0] = Integer.toString(t.getId());
			data[index][1] = t.getSort();
			data[index][2] = Integer.toString(t.getLifespan());
			data[index][3] = Double.toString(t.getCostPrSquareKilometre());
			data[index][4] = Double.toString(t.getRevenuePrSquareKilometre());
			
			index++;
		}
		
		return data;
	}
	
	/**
	 * Sets up the array to combobox
	 * @return
	 */
	public String[] listToArrayCombobox() {
		int index = 0;
		String data[] = new String[tCon.getTrees().size()];
		while(index < tCon.getTrees().size()){
			Tree t = tCon.getTree(index);
			
			data[index] = t.getSort();
			
			index++;
		}
		return data;
	}
}
